<?php

namespace backend\controllers;

use Yii;
use common\models\menu;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SysController implements the CRUD actions for menu model.
 */
class SysController extends AdminController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all menu models.
     * @return mixed
     */
    public function actionIndex()
    {
		$data  = Menu::find()->where('status >= 0');
		// 处理搜索条件
		if (!empty($_GET['title'])) {
			$data->andWhere('title like :title', [':title' => "%{$_GET['title']}%"]);
		}
		if (!empty($_GET['groups'])) {
			$data->andWhere('groups = :groups', [':groups' => $_GET['groups']]);
		}

		$pages = new Pagination([
			'totalCount' => $data->count(),
		]);
		$list = $data->offset($pages->offset)->orderBy('sort')->limit($pages->limit)->all();
		$model = new Menu();
		foreach ($list as $val) {
			if ($val->pid == 0) {
				$val->pname = '无';
				continue;
			}
			/* 获取父类的名称 */
			$val->pname = $model->getPname($val->pid);
		}

		Yii::$app->view->params['titles'] = '菜单管理<span style="font-size: 16px;color: #d9534f">（警告：非专业人员请不要操作这里，会出乱子的噢！）</span>';
        return $this->render('index', [
			'list'  => $list,
			'pages' => $pages
        ]);
    }

    /**
     * Creates a new menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new menu();

        if ($model->load(Yii::$app->request->post()) && $model->add()) {

			Yii::$app->session->setFlash('success', '新增成功');
            return $this->redirect(['index']);
        } else {
			$top = $model->getTopMenu();

			Yii::$app->view->params['titles'] = '新增菜单';
            return $this->render('create', [
                'model' => $model,
				'menu'  => $top
            ]);
        }
    }

    /**
     * Updates an existing menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->edit()) {

			Yii::$app->session->setFlash('success', '更新成功');
            return $this->redirect(['index']);
        } else {
			$menu = $model->getTopMenu();
			Yii::$app->view->params['titles'] = '编辑菜单';
            return $this->render('update', [
                'model' => $model,
				'menu'  => $menu
            ]);
        }
    }

    /**
     * Deletes an existing menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete()
    {
		$id = trim($_REQUEST['id'], ',');
		if (!empty($id)) {

			$result = Menu::updateAll(['status' => -1], "id in({$id})");

			if ($result) {
				Yii::$app->session->setFlash('success', '删除成功');

				if (Yii::$app->request->isAjax) {
					header('Content-type:application/json;charset=utf-8');
					exit(Json::encode(['ret' => '0']));
				}
			} else {
				Yii::$app->session->setFlash('error', '删除失败');

				if (Yii::$app->request->isAjax) {
					exit(Json::encode(['ret' => '1']));
				}
			}
		}
        return $this->redirect(['index']);
    }



    /**
     * Finds the menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
